// src/routes/users.ts
import express, { Request, Response, NextFunction } from "express";
import User from "../models/User";
import { whereParamasHandler } from "@/utils/sequelize";

const router = express.Router();

// 获取用户列表
router.get("/", async (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10 } = req.body;
    const where = whereParamasHandler(
      {},
      {
        page: page,
        pageSize: pageSize,
      }
    );
    const { rows, count } = await User.findAndCountAll(where);
    res.json({
      total: count,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(count / pageSize),
      list: rows,
    });
  } catch (error) {
    res.status(500).json({ message: "Error retrieving users", error });
  }
});

// 查询用户列表
router.post("/", async (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10, userId } = req.body;
    const where = whereParamasHandler(
      {
        username: req.body.username,
        user_id: userId,
        name: req.body.name,
        status: req.body.status,
      },
      {
        page: page,
        pageSize: pageSize,
      }
    );
    const { rows, count } = await User.findAndCountAll(where);
    res.status(200).json({
      total: count,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(count / pageSize),
      list: rows,
    });
  } catch (error) {
    res.status(500).json({ message: "Error retrieving users", error });
  }
});

// 创建新用户
router.post("/add", async (req: Request, res: Response) => {
  const { username, password, name, avatar, role_id, status } = req.body;
  console.log(username, password, name, avatar, role_id, status);
  try {
    const newUser = await User.create({
      username,
      password,
      name,
      avatar,
      role_id,
      status,
    });
    res.status(201).json(newUser);
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ message: "Error creating user", error });
  }
});

// 更改用户
router.patch("/edit", async (req: Request, res: Response) => {
  const { username, userId, password, name, avatar, roleId, status } = req.body;
  console.log(username, password, name, avatar, roleId, status);
  try {
    const user = await User.findByPk(userId);
    if (user) {
      user.avatar = avatar;
      user.password = password;
      user.name = name;
      user.role_id = roleId;
      user.status = status;
      user.save();
      res.status(200).json({ message: "操作成功" });
    } else {
      res.status(400).json({ message: "用户不存在" });
    }
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ message: "Error creating user", error });
  }
});

// 删除用户
router.delete(
  "/delete/:id",
  async (req: Request, res: Response, next: NextFunction) => {
    const { id } = req.params; // 获取要删除的用户 ID
    console.log(id, "id>>");
    try {
      if (!id) {
        res.status(400).json({ message: "参数校验失败" });
      } else {
        const where = whereParamasHandler(
          {
            user_id: id,
          },
          null,
          false
        );

        console.log("where>>", where);
        const deletedCount = await User.destroy(where);
        if (deletedCount === 0) {
          res.status(404).json({ message: "用户不存在或已删除" });
          return;
        }
        res.status(200).json({ message: "用户删除成功" });
      }
    } catch (error) {
      console.error("删除用户失败", error);
      res.status(500).json({ message: "服务器错误", error });
    }
  }
);

export default router;
